package com.android.gardensnake;

import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class SqliteExample extends Activity implements OnClickListener {

	Button sqlAdd, sqlDelete, sqlView;
	EditText sqlFName, sqlLName, sqlRow;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sample_db);
		sqlAdd = (Button) findViewById(R.id.bAdd);
		sqlDelete = (Button) findViewById(R.id.delete);
		sqlView = (Button)findViewById(R.id.bView);		

		sqlFName = (EditText) findViewById(R.id.etFName);
		sqlLName = (EditText) findViewById(R.id.etLName);
		sqlRow = (EditText) findViewById(R.id.etRow);
		
		sqlAdd.setOnClickListener(this);
		sqlDelete.setOnClickListener(this);
		sqlView.setOnClickListener(this);		
	}

	@Override
	public void onClick(View v) {
		boolean didItWork = true;
		switch (v.getId()) {
		case R.id.bView:
			try {
			Intent i = new Intent("com.android.gardensnake.SQLVIEW");
			startActivity(i);
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case R.id.bAdd:
			try {
				String fName = sqlFName.getText().toString();
				String lName = sqlLName.getText().toString();
				DbManager entry = new DbManager(this);
				entry.open();
				entry.createEntry(fName, lName);
				entry.close();
			} catch (Exception e) {
				didItWork = false;
				String error = e.toString();
				Dialog d = new Dialog(this);
				d.setTitle("ERROR");
				TextView tv = new TextView(this);
				tv.setText(error);
				d.setContentView(tv);
				d.show();
			} finally {
				if (didItWork) {
					Dialog d = new Dialog(this);
					d.setTitle("SUCCESS");
					TextView tv = new TextView(this);
					tv.setText("Write to db");
					d.setContentView(tv);
					d.show();
				}
			}
			break;
		case R.id.delete:
			try {
				String sRowId = sqlRow.getText().toString();
				long lRowId = Long.parseLong(sRowId);
				DbManager entry = new DbManager(this);
				entry.open();
				entry.deleteEntry(lRowId);
				entry.close();
			} catch (Exception e) {
				didItWork = false;
				String error = e.toString();
				Dialog d = new Dialog(this);
				d.setTitle("ERROR");
				TextView tv = new TextView(this);
				tv.setText(error);
				d.setContentView(tv);
				d.show();
			} finally {
				if (didItWork) {
					Dialog d = new Dialog(this);
					d.setTitle("SUCCESS");
					TextView tv = new TextView(this);
					tv.setText("Deleted from db");
					d.setContentView(tv);
					d.show();
				}
			}
		}
	}
}
